<?php
namespace app\index\controller;

use app\admin\model\File;
use app\admin\model\Pic;
use app\admin\model\PicType;
use Endroid\QrCode\ErrorCorrectionLevel;
use service\Nearby;
use service\nearby\Point;
use service\Video;
use think\Controller;
use think\facade\Env;
use Endroid\QrCode\QrCode;

class Index extends Controller
{
    public function index(){
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function alipay(){
        $payment = new \app\first\controller\Payment();
        $result = $payment::pay_alipay(build_order_no(),0.01,'测试');
        $qrCode = new QrCode($result['signature']);
        $qrCode->setWriterByName('png');
        $qrCode->setMargin(10);
        $qrCode->setEncoding('UTF-8');
        $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::LOW());
//        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
//        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        // header('Content-Type: '.$qrCode->getContentType());
        echo "<img src='{$qrCode->writeDataUri()}' width='350' height='350'/>";
    }
    /**
     * @throws \Exception
     */
    public function aac(){
        $vod = new Video();
        $source = \env('app_path').'../data/test.flv';
        $result = $vod
            ->setPath($source)
            ->setLibx264()
            ->setThreads(5)
            ->setSize()
            ->createCmd()
            ->convert()
            ->getResult();
        return json($result);
    }

    public function location(){
//        $content = file_get_contents('../data/list.json');
//        $data = [];
//        $content = json_decode($content, true);
//        foreach ($content as $k => $v){
//            array_push($data,[
//                'name'=>$v,
//                'code'=>$k,
//                'create_time'=>time(),
//                'status'=>1,
//            ]);
//        }
//        //p($data1);
//        db('region')->insertAll($data);
        $data1 = [];
        $handle = fopen('../data/region_code.data',"r");
        while(!feof($handle)){//函数检测是否已到达文件末尾
            if($content1 = fgets($handle)){// 从文件指针中读取一行
                $content1 = explode('|',$content1);
                $key = trim_all($content1[1]);
                if(strpos($key,'市')!==false){
                    $key = str_replace('市','',$key);
                }else if(strpos($key,'自治州')!==false){
                    $key = str_replace('自治州','',$key);
                }else if(strpos($key,'地区')!==false){
                    $key = str_replace('地区','',$key);
                }else if(strpos($key,'自治区')!==false){
                    $key = str_replace('自治区','',$key);
                }
                db('region')
                    ->whereLike('name',"%{$key}%")
                    ->setField('getui_code',$content1[0]);
            };
        }
        fclose($handle);
        echo '操作成功';
    }

    /**
     * 阿里云OSS回调
     */
    public function callback(){
        $authorizationBase64 = Env::get('ALIYUN.ALIYUN_ACCESS_KEY_ID');
        $pubKeyUrlBase64 = Env::get('ALIYUN.ALIYUN_ACCESS_KEY_SECRET');
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
        }
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL'])) {
            $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        }

        if ($authorizationBase64 == '' || $pubKeyUrlBase64 == '') {
            header("http/1.1 403 Forbidden");
            exit();
        }

        // 2.获取OSS的签名
        $authorization = base64_decode($authorizationBase64);
        // 3.获取公钥
        $pubKeyUrl = base64_decode($pubKeyUrlBase64);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $pubKey = curl_exec($ch);
        if ($pubKey == "") {
            header("http/1.1 403 Forbidden");
            exit();
        }
        $body = file_get_contents('php://input');
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false) {
            $authStr = urldecode($path)."\n".$body;
        } else {
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }
        $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($ok == 1) {
            header("Content-Type: application/json");
            $filename = $_POST['filename'];
            $_data = [];
            if(strpos($_POST['mimeType'],'video')!==false){
//                $type = 'video';
                $file = new File();
                $path = Env::get('ALIYUN.ALIYUN_HOST'). '/'.$filename;
                $id = $file->addNew($filename,$path,$_POST['type_id'],'','',$_POST['size'],'');
                if(!$id){
                    $json = \GuzzleHttp\json_encode([
                        'status'=>0,
                        'msg'=> '上传失败'
                    ]);
                    exit($json);
                }
                $_data['_id'] = intval($id);
                $_data['_path'] = $path;
            }else{
//                $type = 'image';
                $pic = new Pic();
                $pic_type = (new PicType)->get($_POST['type_id']);
                 // https://jiexun.oss-cn-hangzhou.aliyuncs.com/resource_water/dav-resource_water19082015534142186.jpg@!resource_water
                if(strpos($pic_type['finder_name'],'%Ym%')>-1){
                    $pic_type['finder_name'] = str_replace('%Ym%','',$pic_type['finder_name']);
                }
                $path = Env::get('ALIYUN.ALIYUN_HOST'). '/'.$filename.'@!'.$pic_type['finder_name'];
                $id = $pic->addNew($filename,$path,$_POST['type_id'],$_POST['width'],$_POST['height'],$_POST['size'],'');
                if(!$id){
                     $json = \GuzzleHttp\json_encode([
                        'status'=>0,
                        'msg'=> '上传失败'
                     ]);
                     exit($json);
                }
                $_data['_id'] = intval($id);
                $_data['_path'] = $path;
            }
            $data = [
                "status"=>1,
                'msg'=>'上传成功',
                'data'=>$_data
            ];
            echo json_encode($data);
        } else {
            header("http/1.1 403 Forbidden");
            exit();
        }
    }

    /**
     *
     */
    public function test(){
        $nearby = new Nearby();
        $point = new Point('116.403039','39.913359','beijing');
        $point1 = new Point('120.587813','31.305293','suzhou');
        $point2 = new Point('121.474216','31.236176','shanghai');
        $point3 = new Point('117.293449','34.210039','xuzhou');
        $points = [$point,$point1,$point2,$point3];
//        $result = $nearby->addPos($point);
//        $result = $nearby->setIsDB(true)->addPosList($points);  //添加坐标点
//        $result1 = $nearby->getPosMemberByRadius($nearby->getLocationByMember('suzhou'),'150','km'); // 根据中心点获取附近点
//        $result2 = $nearby->getPosMemberByMember('suzhou','100','km'); // 根据城市获取附近点
//        $result3 = $nearby->getDistance('suzhou','xuzhou','km'); // 根据成员名计算距离
//        $result = $nearby->getDistanceByPoint($point,$point1,'km'); // 根据坐标计算距离
//        $result = $nearby->remove('beijing'); // 移除指定成员
//        $result =  $nearby->clear(); // 清除数据
        $result =  $nearby->all(); // 获取所有成员
        $data['status'] = 1;
        $data['data'] = $result;
        return json($data);
    }
}
